from server import PromptServer
from aiohttp import web
import os

@PromptServer.instance.routes.get("/api/clean_usedata")
async def clean_usedata(request):
    try:
        # json_data = await request.json()
        
        # 处理自定义逻辑
        result = await process_custom_request()
        
        return web.json_response(result, status=200)
    except Exception as e:
        return web.json_response({"error": str(e)}, status=400)

async def process_custom_request():
    """处理自定义请求，清理input、output、output/video、temp下的图片和视频文件"""
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
    print(f"Base directory: {base_dir}")
    targets = [
        os.path.join(base_dir, "input"),
        os.path.join(base_dir, "output"),
        os.path.join(base_dir, "output", "video"),
        os.path.join(base_dir, "temp"),
    ]
    # 支持的图片和视频扩展名
    img_exts = ['.jpg', '.jpeg', '.png', '.webp', '.bmp']
    video_exts = ['.mp4', '.avi', '.mov', '.mkv']

    deleted_files = []

    for folder in targets:
        if not os.path.exists(folder):
            continue
        for fname in os.listdir(folder):
            fpath = os.path.join(folder, fname)
            if not os.path.isfile(fpath):
                continue
            ext = os.path.splitext(fname)[1].lower()
            if ext in img_exts or ext in video_exts:
                try:
                    os.remove(fpath)
                    deleted_files.append({"path": folder, "name": fname})
                except Exception as e:
                    # 可以记录异常或返回错误信息
                    pass

    return {"status": "success", "deleted": deleted_files}
